package com.example.business.service.impl;

import com.example.business.dao.entity.Diary;
import com.example.business.dao.mapper.DiaryMapper;
import com.example.business.service.DiaryService;
import com.example.business.dao.dto.DiarySubmitDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class DiaryServiceImpl implements DiaryService {
    private final DiaryMapper diaryMapper;
    // 日期格式化器（Java 8兼容）
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    @Override
    public ResponseEntity<String> writeDown(DiarySubmitDTO dto) {
        try {
            LocalDate today = LocalDate.now();
            // 1. 查询当天是否已有日记
            Diary existingDiary = diaryMapper.selectByRecordDate(today);

            Diary diary = new Diary();
            diary.setContent(dto.getContent());
            diary.setWeather(dto.getWeather());
            diary.setRecordDate(today);

            if (existingDiary != null) {
                // 2. 已有日记则更新
                diary.setId(existingDiary.getId()); // 复用ID
                diaryMapper.updateById(diary);
                return ResponseEntity.ok("日记更新成功");
            } else {
                // 3. 无日记则新增
                diaryMapper.insert(diary);
                return ResponseEntity.ok("日记保存成功");
            }
        } catch (Exception e) {
            log.error("保存日记失败", e);
            return ResponseEntity.status(500).body("保存日记失败：" + e.getMessage());
        }
    }

    @Override
    public List<String> someDays() {
        // 查询最近7天的日记
        List<Diary> diaries = diaryMapper.selectRecentDiaries(7);
        List<String> result = new ArrayList<>();

        for (Diary diary : diaries) {
            // 格式化：日期 天气：内容
            String item = String.format("%s %s：%s",
                    diary.getRecordDate().format(DATE_FORMATTER),
                    diary.getWeather(),
                    diary.getContent());
            result.add(item);
        }
        return result;
    }
}
